package org.piggy.core.filter.loadbalance.rule;

import org.piggy.common.config.ServiceInstance;
import org.piggy.common.enums.ResponseCode;
import org.piggy.common.exception.PiggyException;
import org.piggy.core.context.GatewayContext;
import org.piggy.core.manager.DynamicConfigManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinLoadBalanceRule implements LoadBalanceGatewayRule {

    private final AtomicInteger currentIndex = new AtomicInteger(0);

    private RoundRobinLoadBalanceRule(){}

    private static final RoundRobinLoadBalanceRule roundRobinLoadBalanceRule = new RoundRobinLoadBalanceRule();

    public static RoundRobinLoadBalanceRule getInstance (){
        return roundRobinLoadBalanceRule;
    }

    @Override
    public ServiceInstance choose(GatewayContext context) {
        Set<ServiceInstance> servers = DynamicConfigManager.getInstance().getServiceInstanceByServiceName(context.getRule().getServiceName(), context.isGray());
        if (servers.isEmpty()) {
            throw new PiggyException(ResponseCode.SERVICE_INSTANCE_NOT_FOUND);
        }
        int size = servers.size();
        int num = currentIndex.getAndIncrement();
        int index = Math.floorMod(num, size);
        List<ServiceInstance> instances = new ArrayList<>(servers);
        return instances.get(index);
    }

}
